<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <div class="title">欢迎登录</div>
      <div class="login-type">
        <div
          v-for="(item, index) in loginType"
          :key="index"
          class="type-item"
          :style="{ color: item.value === loginTypeValue ? $store.state.settings.theme : '#a0a0a0' }"
          @click="handleLoginType(item)"
        >
          {{ item.name }}
          <div
            class="item-line"
            :style="{ width: item.value === loginTypeValue ? '60px' : '0', backgroundColor: $store.state.settings.theme }"
          ></div>
        </div>
      </div>
      <template v-if="loginTypeValue === 'account'">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item v-if="captchaEnabled" prop="code">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 73%"
            maxlength="6"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" class="login-code-img" @click="getCode" />
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px">记住密码</el-checkbox>
      </template>
      <template v-else>
        <el-form-item key="phone" prop="phone">
          <el-input
            v-model="loginForm.phone"
            type="text"
            auto-complete="off"
            placeholder="手机号"
            maxlength="11"
            @input="loginForm.phone = $event.replace(/[\W]/g, '')"
          >
            <svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item key="code" prop="code">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 73%"
            maxlength="6"
            @keyup.enter.native="handleLogin"
            @input="loginForm.code = $event.replace(/[\W]/g, '')"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <el-button class="phone-code" :disabled="isSend" type="primary" @click="getPhoneCode">
            {{ isSend ? `${second}s后重新获取` : '获取验证码' }}
          </el-button>
        </el-form-item>
      </template>

      <el-form-item style="width: 100%; margin-top: 35px">
        <el-button :loading="loading" size="medium" type="primary" style="width: 100%" @click.native.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div v-if="register" style="float: right">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getCodeImg, sendSms } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: 'Login',
  data() {
    return {
      codeUrl: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: '',
        loginType: 1
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
        password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
        code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
        phone: [{ required: true, trigger: 'blur', message: '请输入您的手机号' }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      loginType: [
        { name: '账户登录', value: 'account' }
        // { name: '手机号登录', value: 'phone' }
      ],
      loginTypeValue: 'account',
      isSend: false,
      second: 60,
      timer: null
    }
  },
  watch: {
    $route: {
      handler(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.getCode()
    this.getCookie()
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.loginForm.uuid = res.uuid
        }
      })
    },
    getCookie() {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        loginType: 1
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.loginTypeValue === 'account') {
            if (this.loginForm.rememberMe) {
              Cookies.set('username', this.loginForm.username, { expires: 30 })
              Cookies.set('password', encrypt(this.loginForm.password), { expires: 30 })
              Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
            } else {
              Cookies.remove('username')
              Cookies.remove('password')
              Cookies.remove('rememberMe')
            }
          }
          this.$store
            .dispatch(this.loginTypeValue === 'account' ? 'Login' : 'PhoneLogin', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/' }).catch(() => {})
            })
            .catch(() => {
              this.loading = false
              if (this.captchaEnabled && this.loginTypeValue === 'account') {
                this.getCode()
              }
            })
        }
      })
    },

    handleLoginType(val) {
      this.loginTypeValue = val.value
    },

    timerGo() {
      this.timer = setInterval(() => {
        this.second--
        if (this.second <= 0) {
          this.second = 60
          clearInterval(this.timer)
          this.isSend = false
        }
      }, 1000)
    },

    getPhoneCode() {
      if (this.isSend) return
      if (!this.loginForm.phone) return this.$modal.msgError('请输入您的手机号')
      if (!/^1[3-9]\d{9}$/.test(this.loginForm.phone)) return this.$modal.msgError('请输入正确的手机号')
      sendSms(this.loginForm.phone).then(res => {
        console.log('发送验证码', res)
        if (res?.code === 200) {
          this.loginForm.uuid = res?.data?.uuid
          this.isSend = true
          this.second = 60
          this.timerGo()
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  background-image: url('../assets/images/login-background.jpg');
  background-size: cover;
  background-repeat: no-repeat;
  padding-right: 100px;
}
.title {
  // margin: 0px auto 30px auto;
  // text-align: center;
  color: #0a0a0a;
  font-size: 50px;
  margin-bottom: 50px;
}

.login-form {
  border-radius: 6px;
  // background: #ffffff;
  background-color: rgba(255, 255, 255, 0.5);
  width: 710px;
  height: 670px;
  box-sizing: border-box;
  padding: 80px;
  .el-input {
    height: 50px;
    input {
      height: 50px;
    }
  }
  .input-icon {
    height: 50px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 23%;
  height: 50px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  width: 100%;
  height: 48px;
}
.login-type {
  display: flex;
  align-items: center;
  column-gap: 60px;
  margin-bottom: 32px;
  .type-item {
    color: #a0a0a0;
    font-size: 24px;
    cursor: pointer;
    position: relative;
  }
  .item-line {
    position: absolute;
    left: 50%;
    bottom: -10px;
    transform: translateX(-50%);
    width: 60px;
    height: 6px;
    border-radius: 10px;
    // background-color: #3974f2;
    transition-property: width;
    transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
    transition-duration: 300ms;
  }
  .active-type {
    color: #3974f2;
  }
}
.phone-code {
  width: 23%;
  height: 50px;
  line-height: 50px;
  text-align: center;
  float: right;
  background-color: red;
}
</style>
